﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Data.SqlClient;
using System.Configuration;

namespace ECSS.Winform
{
    public partial class ReBuildBossOrder : Form
    {
        public ReBuildBossOrder()
        {
            InitializeComponent();
        }

        private void splitContainer1_Panel2_Paint(object sender, PaintEventArgs e)
        {

        }

        private void splitContainer1_Panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Enabled = false;

            if (!string.IsNullOrEmpty(txtOrderIDs.Text.Trim())
                && txtOrderIDs.Lines.Count() > 0)
            {
                for (int i = 0; i < txtOrderIDs.Lines.Count(); i++)
                {
                    string orderid = txtOrderIDs.Lines[i];
                    if (string.IsNullOrEmpty(orderid)) continue;
                    try
                    {
                        // 重新生成BOSS预订单
                        var newBossOrderID = GetNewBossOrderID(orderid);

                        // 将预订单更新到OrderBOSSIncome
                        UpdateBOSSIncome(newBossOrderID, orderid);


                        listBox1.Items.Add(string.Format("处理{0}成功,生成BOSSOrderID:{1}", orderid, newBossOrderID));
                    }
                    catch (Exception ex)
                    {
                        listBox1.Items.Add(string.Format("处理{0}失败,原因:{1}", orderid, ex.Message));
                    }

                    listBox1.Update();

                    Thread.Sleep(1000);
                }
            }


            this.Enabled = true;
        }

        private void UpdateBOSSIncome(string bossOrderID, string orderID)
        {
            if (!string.IsNullOrEmpty(bossOrderID))
            {
                const string sql = @"update OrderBOSSIncome set CreatTime=GETDATE(),Status=0,BOSSOrderID=@BOSSOrderID 
                                where BOSSOrderType=1 and OrderID=@OrderID";

                var sqlconn = new SqlConnection
                {
                    ConnectionString = ConfigurationManager.ConnectionStrings["ECSSDb"].ConnectionString

                };

                var sqlcmd = new SqlCommand
                {
                    Connection = sqlconn,
                    CommandText = sql
                };


                sqlcmd.Parameters.Add("@BOSSOrderID", SqlDbType.NVarChar, 32);
                sqlcmd.Parameters["@BOSSOrderID"].Value = bossOrderID;

                sqlcmd.Parameters.Add("@OrderID", SqlDbType.NVarChar, 16);
                sqlcmd.Parameters["@OrderID"].Value = orderID;

                try
                {
                    sqlcmd.Connection.Open();
                    sqlcmd.ExecuteNonQuery();
                }
                finally
                {
                    sqlcmd.Connection.Close();
                }

            }

        }

        private string GetNewBossOrderID(string orderID)
        {
            const string sql = @"select a.OrderID,c.CerficationCode,a.UserMobile from OrderInfo a 
                                join OrderOffering b
                                on a.OrderID=b.OrderID
                                join OfferingPrice c
                                on b.OfferingID=c.OfferingID
                                where a.OrderID=@OrderID";

            string bossSaleCode = string.Empty;
            string mobile = string.Empty;

            var sqlconn = new SqlConnection
            {
                ConnectionString = ConfigurationManager.ConnectionStrings["ECSSDb"].ConnectionString

            };

            var sqlcmd = new SqlCommand
            {
                Connection = sqlconn,
                CommandText = sql
            };

            sqlcmd.Parameters.Add("@OrderID", SqlDbType.NVarChar, 16);
            sqlcmd.Parameters["@OrderID"].Value = orderID;

            try
            {
                sqlcmd.Connection.Open();
                var sqlrd = sqlcmd.ExecuteReader();
                if (sqlrd.HasRows)
                {
                    sqlrd.Read();
                    bossSaleCode = sqlrd["CerficationCode"].ToString();
                    mobile = sqlrd["UserMobile"].ToString();
                }
            }
            finally
            {
                sqlcmd.Connection.Close();
            }


            if (!string.IsNullOrEmpty(bossSaleCode))
            {
                var wcf = new BOSSInterfaceInvoke();


                var bossRequest = new BOSSPreOrderRequestEntity();
                var plans = new List<MarketingPlanInfoEntity>();

                plans.Add(new MarketingPlanInfoEntity
                {
                    BOSSResCodek__BackingField = "*",
                    BOSSSaleCodek__BackingField = bossSaleCode
                });

                bossRequest.Mobilek__BackingField = mobile;
                bossRequest.Amountk__BackingField = 0;
                bossRequest.MarketingPlans = plans.ToArray();

                var bossResponse = wcf.CreatePreOrder(bossRequest);

                if (bossResponse != null)
                {
                    if (bossResponse.Succeedk__BackingField)
                    {

                        if (bossResponse.ReserveOrderItemsk__BackingField == null ||
                                         bossResponse.ReserveOrderItemsk__BackingField.Length == 0)
                        {
                            throw new Exception(string.Format("调用BOSS接口生成资格认证预订单异常，未返回预订单号"));
                        }

                        if (!string.IsNullOrEmpty(bossResponse.PreOrderIDk__BackingField))
                        {
                            return bossResponse.PreOrderIDk__BackingField;
                        }

                    }
                    else
                    {
                        throw new Exception(string.Format("重新生成BOSS接口资格认证预订单失败，原因{0},{1}", bossResponse.ErrorMessagek__BackingField, bossResponse.Messagek__BackingField));
                    }
                }
            }

            return string.Empty;
        }
    }
}
